/*
 * @Author: Leng
 * @Date: 2023-04-07 15:00:09
 * @Description: 请求拦截, 响应拦截
 * @use README.md 文档介绍
 * @FilePath: \leng-request\src\utils\request.js
 */

import axios from "axios"

// 实例, 拦截器
class requestConfig {
  constructor() {
    const instance = axios.create({
      // baseURL: 'https://leng.com',
      // 跨域请求时是否需要使用凭证, 默认false
      // withCredentials: true,
      // headers: {
      // 	'Access-Control-Allow-Credentials': "false",
      // 	'Access-Control-Allow-Origin': '*'
      // },
      timeout: 1000 * 10
    })
    /* eslint-disable no-proto */
    // instance.__proto__ = axios
    /* eslint-enable */
    // 请求拦截
    instance.interceptors.request.use(
      (config) => {
        // config.headers['ismock'] = false
        return config
      },
      (error) => {
        console.log(error)
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      (response) => {
        const res = response.data
        if (res.code == "-99") {
          console.log(`未登录：${window.location.origin}/login`)
          return Promise.reject(new Error(res.message || "Error"))
        } else {
          return response
        }
      },
      (error) => {
        console.log("err" + error)
        return Promise.reject(error)
      }
    )
    // 实例
    this.instance = instance
  }
}

// 请求封装
class instanceCreate extends requestConfig {
  constructor() {
    super()
  }
  // get请求
  get(url, params, config) {
    let _params = params ? { params } : {}
    let param = Object.assign({}, _params, config)
    return this.instance.get(url, param).then((res) => {
      return Promise.resolve((res && res.data) || {})
    })
      .catch((err) => {
        console.error(err)
        return Promise.resolve({
          code: "-404",
          msg: err.message || "网络异常",
        })
      })
  }

  // post请求
  post(url, data, config = {}) {
    return this.instance.post(url, data, config).then((res) => {
      return Promise.resolve((res && res.data) || {})
    })
      .catch((err) => {
        console.error(err)
        return Promise.resolve({
          code: "-404",
          msg: err.message || "网络异常",
        })
      })
  }

  // 导出配置
  instanceConfig() {
    return {
      get: (...args) => {
        return this.get(...args)
      },
      post: (...args) => {
        return this.post(...args)
      },
      cancelToken: axios.CancelToken,
      instance: this.instance
    }
  }
}

// 导出配置
const apiConfig = new instanceCreate()
const apiRequest = apiConfig.instanceConfig()
// apiRequest.instance.defaults.baseURL = 'https://test.cn'

// 原有继承方式, 兼容extend形式
class api {
  static get(...args) {
    return apiRequest.get(...args)
  }

  static post(...args) {
    return apiRequest.post(...args)
  }
}

// 导出
export {
  api,
  apiRequest
}
